﻿using FineUIPro;
using KPI_SYSTEM.Code;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace KPI_SYSTEM.ApprovalPage
{
    public partial class ApprovalListPage : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadBaseData();
                BindData();
            }
            PublicMethod.GetApprovalButton("ApprovalListPage.aspx", Toolbar2, Grid1);
        }
        /// <summary>
        /// 加载页面必备数据
        /// </summary>
        private void LoadBaseData()
        {
            DataTable tableDept = SqlHelper.ExecuteDataset(CommandType.Text, @"SELECT REC_ID,DEPT_NAME FROM DEPT_DICT WHERE PARENT_ID=0 AND DEPT_STATUS=1").Tables[0];
            ddlSearchSUB_DEPT.DataTextField = "DEPT_NAME";
            ddlSearchSUB_DEPT.DataValueField = "REC_ID";
            ddlSearchSUB_DEPT.DataSource = tableDept;
            ddlSearchSUB_DEPT.DataBind();
            FineUIPro.ListItem searchDeptItem = new FineUIPro.ListItem();
            searchDeptItem.Value = "0";
            searchDeptItem.Text = "选择部门";
            ddlSearchSUB_DEPT.Items.Insert(0, searchDeptItem);
        }
        /// <summary>
        /// 加载页面列表数据
        /// </summary>
        private void BindData()
        {
            
            StringBuilder sqlWhere = new StringBuilder();
            String mainDataSql = @"SELECT A.REC_ID,(SELECT PROCESS_SEQ FROM HOS_APPROVAL_PROCESS WHERE REC_ID=A.PROCESS_ID) AS PROCESS_SEQ,
                                    (SELECT USER_NAME FROM USER_DICT WHERE REC_ID=A.SUB_USER) AS SUB_USER_NAME,
                                    (SELECT DEPT_NAME FROM DEPT_DICT WHERE REC_ID=A.SUB_DEPT) AS SUB_DEPT_NAME,
                                    A.APPROVAL_CONTENT,A.CREATE_TIME,(SELECT DICT_NAME FROM SYSTEM_DICT WHERE REC_ID=A.PROCESS_TYPE) AS PROCESS_TYPE_NAME,
                                    CASE WHEN A.PROCESS_RESULT=0 THEN '待审核' WHEN A.PROCESS_RESULT=1 THEN '已同意' 
                                    WHEN A.PROCESS_RESULT=2 THEN '已驳回' ELSE '待审核' END AS PROCESS_RESULT_NAME,
                                    A.APPROVAL_ID,A.PROCESS_ID,A.APPROVAL_DATA_ID,A.PROCESS_OPINION,A.SUB_DEPT,A.SUB_USER
                                     FROM HOS_APPROVAL_RECORDS AS A WHERE 1=1 {0} ";
            if (ddlSearchPROCESS_RESULT.SelectedValue != "" && ddlSearchPROCESS_RESULT.SelectedValue != null)
            {
                sqlWhere.Append(" AND A.PROCESS_RESULT =" + ddlSearchPROCESS_RESULT.SelectedValue);
            }
            if (ddlSearchSUB_DEPT.SelectedValue != "0" && ddlSearchSUB_DEPT.SelectedValue != null)
            {
                sqlWhere.Append(" AND A.SUB_DEPT =" + ddlSearchSUB_DEPT.SelectedValue);
            }
            if (Session["RoleID"].ToString() != "1")
            {
                sqlWhere.Append(" AND A.PROCESS_USER = " + Session["UserID"].ToString());
            }
            mainDataSql = string.Format(mainDataSql, sqlWhere.ToString());
            DataTable mainDataTable = SqlHelper.ExecuteDataset(CommandType.Text, mainDataSql).Tables[0];
            Grid1.DataSource = mainDataTable;
            Grid1.DataBind();
        }
        private void ApprovalFormBind(GridRow gridRow)
        {
            String approvalID = gridRow.Values[7].ToString();
            String processID = gridRow.Values[8].ToString();
            String approvalDataID = gridRow.Values[9].ToString();
            String subDeptID = gridRow.Values[10].ToString();
            String subUserID = gridRow.Values[11].ToString();
            String sql = @"SELECT A.REC_ID,(SELECT PROCESS_SEQ FROM HOS_APPROVAL_PROCESS WHERE REC_ID=A.PROCESS_ID) AS PROCESS_SEQ,
								  (SELECT DEPT_NAME FROM DEPT_DICT WHERE REC_ID=A.PROCESS_DEPT) AS PROCESS_DEPT_NAME,
                                  (SELECT DICT_NAME FROM SYSTEM_DICT WHERE REC_ID=A.PROCESS_TYPE) AS PROCESS_TYPE_NAME,
						          (SELECT USER_NAME FROM USER_DICT WHERE REC_ID=A.PROCESS_USER) AS PROCESS_USER_NAME,
                                  CASE WHEN A.PROCESS_RESULT=0 THEN '待审核' WHEN A.PROCESS_RESULT=1 THEN '已同意' 
                                    WHEN A.PROCESS_RESULT=2 THEN '已驳回' ELSE '待审核' END AS PROCESS_RESULT_NAME,
                                  A.PROCESS_OPINION,A.UPDATE_TIME,A.PROCESS_USER,A.SUB_TIME,A.APPROVAL_CONTENT, 
                                (SELECT DEPT_NAME FROM DEPT_DICT WHERE REC_ID=A.SUB_DEPT) AS SUB_DEPT_NAME, 
                                (SELECT USER_NAME FROM USER_DICT WHERE REC_ID=A.SUB_USER) AS SUB_USER_NAME
                                FROM HOS_APPROVAL_RECORDS AS A 
                                WHERE A.APPROVAL_ID={0} AND A.APPROVAL_DATA_ID={1} AND A.SUB_DEPT={2} AND A.SUB_USER={3}";
            sql = string.Format(sql, approvalID, approvalDataID, subDeptID, subUserID);
            DataTable dataTable = SqlHelper.ExecuteDataset(CommandType.Text, sql).Tables[0];
            GridProcess.DataSource = dataTable;
            GridProcess.DataBind();
            tbxFormSUB_DEPT_NAME.Text = dataTable.Rows[0]["SUB_DEPT_NAME"].ToString();
            tbxFormSUB_USER_NAME.Text = dataTable.Rows[0]["SUB_USER_NAME"].ToString();
            tbxFormSUB_TIME.Text = dataTable.Rows[0]["SUB_TIME"].ToString();
            tbxFormAPPROVAL_CONTENT.Text = dataTable.Rows[0]["APPROVAL_CONTENT"].ToString();
        }
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindData();
        }

        protected void btnEditApprovalMessage_Click(object sender, EventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length > 0)
            {
                GridRow gridRow = Grid1.SelectedRow;
                ApprovalFormBind(gridRow);
                PageContext.RegisterStartupScript(String.Format("F('{0}').show();", Window1.ClientID));
            }
            else
            {
                ShowNotify("未选中任何行!");
            }
        }

        protected void GridProcess_RowClick(object sender, GridRowClickEventArgs e)
        {
            GridRow gridRow = GridProcess.SelectedRow;
            String userID = gridRow.Values[7].ToString();
            if (userID != Session["UserID"].ToString())
            {
                ShowNotify("非您审批结果，不可修改");
                return;
            }
            String strRowID = GridProcess.DataKeys[e.RowIndex][0].ToString();
            hfFormID.Text = strRowID;
            DataTable dataTable = SqlHelper.ExecuteDataset(CommandType.Text, "SELECT PROCESS_RESULT,PROCESS_OPINION FROM HOS_APPROVAL_RECORDS WHERE REC_ID=" + strRowID).Tables[0];
            rblFormPROCESS_RESULT.SelectedValue = dataTable.Rows[0]["PROCESS_RESULT"].ToString();
            tbxFormPROCESS_OPINION.Text = dataTable.Rows[0]["PROCESS_OPINION"].ToString();

        }
        protected void btnSaveApproval_Click(object sender, EventArgs e)
        {
            GridRow gridRow = Grid1.SelectedRow;
            Int32 processSeq = Convert.ToInt32(gridRow.Values[0].ToString());
            String approvalID = gridRow.Values[7].ToString();
            String processID = gridRow.Values[8].ToString();
            String approvalDataID = gridRow.Values[9].ToString();
            String subDeptID = gridRow.Values[10].ToString();
            String subUserID = gridRow.Values[11].ToString();
            String sqlLast = @"SELECT TOP 1 PROCESS_RESULT FROM HOS_APPROVAL_RECORDS WHERE APPROVAL_ID={0} AND
                                 APPROVAL_DATA_ID={1} AND SUB_DEPT={2} AND SUB_USER={3} AND PROCESS_SEQ={4} ORDER BY PROCESS_RESULT ";
            sqlLast = string.Format(sqlLast, approvalID, approvalDataID, subDeptID, subUserID, processSeq - 1);
            object strLastResult = SqlHelper.ExecuteScalar(CommandType.Text, sqlLast);
            if (strLastResult != null)
            {
                Int32 lastResult = Convert.ToInt32(strLastResult);
                if (lastResult == (int)PROCESS_RESULT.待审核)
                {
                    ShowNotify("上一步未审批，您暂不可审批!");
                    return;
                }
                else if (lastResult == (int)PROCESS_RESULT.审核未通过)
                {
                    ShowNotify("上一步审批已驳回，您暂不可审批!");
                    return;
                }
            }
            String sqlNext = @"SELECT TOP 1 PROCESS_RESULT FROM HOS_APPROVAL_RECORDS WHERE APPROVAL_ID={0} AND
                                 APPROVAL_DATA_ID={1} AND SUB_DEPT={2} AND SUB_USER={3} AND PROCESS_SEQ={4} ORDER BY PROCESS_RESULT ";
            sqlNext = string.Format(sqlNext, approvalID, approvalDataID, subDeptID, subUserID, processSeq + 1);
            object strNextResult = SqlHelper.ExecuteScalar(CommandType.Text, sqlNext);
            if (strNextResult != null)
            {
                Int32 nextResult = Convert.ToInt32(strNextResult);
                if (rblFormPROCESS_RESULT.SelectedValue != "" && rblFormPROCESS_RESULT.SelectedValue != null)
                {
                    Int32 editResult = Convert.ToInt32(rblFormPROCESS_RESULT.SelectedValue);
                    if (editResult == (int)PROCESS_RESULT.审核未通过)
                    {
                        if (nextResult == (int)PROCESS_RESULT.审核通过)
                        {
                            ShowNotify("下一步审批已通过，不可修改结果!");
                            return;
                        }
                    }
                }
            }


            Dictionary<String, String> keyValuePairs = new Dictionary<string, string>();
            keyValuePairs.Clear();

            if (rblFormPROCESS_RESULT.SelectedValue != "" && rblFormPROCESS_RESULT.SelectedValue != null)
            {
                keyValuePairs.Add("PROCESS_RESULT", rblFormPROCESS_RESULT.SelectedValue);
            }
            else
            {
                ShowNotify("审批结果不能为空!");
                return;
            }
            keyValuePairs.Add("PROCESS_OPINION", tbxFormPROCESS_OPINION.Text);
            String strRowID = Grid1.SelectedRowID;
            keyValuePairs.Add("REC_ID", strRowID);
            keyValuePairs.Add("UPDATE_TIME", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            keyValuePairs.Add("UPDATE_USER", Session["UserID"].ToString());
            PublicMethod.SetDataMethod("SELECT * FROM HOS_APPROVAL_RECORDS WHERE REC_ID=" + strRowID, "Update", keyValuePairs);
            PublicMethod.SetDataMethod("SELECT * FROM HOS_APPROVAL_RECORDS_BAK WHERE RECORD_ID=" + strRowID, "Update", keyValuePairs);
            ApprovalFormBind(gridRow);
            hfFormID.Text = "";
            tbxFormPROCESS_OPINION.Text = "";
            rblFormPROCESS_RESULT.SelectedValue = "";
            ShowNotify("保存成功!");

        }
        
        protected void rblFormPROCESS_RESULT_SelectedIndexChanged(object sender, EventArgs e)
        {
            tbxFormPROCESS_OPINION.Text = rblFormPROCESS_RESULT.SelectedItem.Text;
        }
    }
}